//
//  HXTagsView.m
//  黄轩 https://github.com/huangxuan518
//
//  Created by 黄轩 on 16/1/13.
//  Copyright © 2015年 IT小子. All rights reserved.
//

#import "HXTagsView.h"
#import "HXTagCollectionViewCell.h"
#import "HXTagAttribute.h"

@interface HXTagsView () <UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic,strong) UICollectionView *collectionView;
@end

@implementation HXTagsView

static NSString * const reuseIdentifier = @"HXTagCollectionViewCellId";

- (id)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    return self;
}

- (void)setup{
    //初始化样式
    self.backgroundColor = UIColor.whiteColor;
//    _tagAttribute = [HXTagAttribute new];
    _layout = [[HXTagCollectionViewFlowLayout alloc] init];
    [self addSubview:self.collectionView];
}

- (void)reloadData {
    [self.collectionView reloadData];
}

- (void)setScrollEnabled:(BOOL)scrollEnabled{
    self.collectionView.scrollEnabled = scrollEnabled;
}

- (void)setAllowsSelection:(BOOL)allowsSelection{
    self.collectionView.allowsSelection = allowsSelection;
}

- (void)setDefaultSelectedIndex:(NSInteger)selectedIndex{
    [self.selectedTags removeAllObjects];
    [self.selectedTags addObject:self.tags[selectedIndex]];
}

#pragma mark - UICollectionViewDelegate | UICollectionViewDataSource
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HXTagCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.viewBox.backgroundColor = _tagAttribute.normalBackgroundColor;
    cell.viewBox.layer.borderColor = _tagAttribute.borderColor.CGColor;
    cell.viewBox.layer.cornerRadius = _tagAttribute.cornerRadius;
    cell.viewBox.layer.borderWidth = _tagAttribute.borderWidth;
    cell.titleLabel.textColor = _tagAttribute.textColor;
    cell.titleLabel.font = [UIFont systemFontOfSize:_tagAttribute.titleSize];

    cell.close.hidden = !_tagAttribute.haveCloseBtn;
    if (_tagAttribute.haveCloseBtn) {
        cell.viewBox.frame = CGRectMake(0, 5,
                                        cell.bounds.size.width-_tagAttribute.closeBtnWidth+_tagAttribute.closeBtnIgnoreWidth+2,
                                        cell.bounds.size.height-5);
        CGFloat wh = _tagAttribute.closeBtnWidth;
        cell.close.frame = CGRectMake(cell.bounds.size.width-wh, 0, wh, wh);
        if (_tagAttribute.closeImage) {
            cell.close.image = [UIImage imageNamed:self.tagAttribute.closeImage];
        }
    }else{
        cell.viewBox.frame = cell.bounds;
    }
    
    cell.titleLabel.frame = cell.viewBox.bounds;
    
    if (self.tags.count > indexPath.item) {
        NSString *title = self.tags[indexPath.item];
        if (_key.length > 0) {
            cell.titleLabel.attributedText = [self searchTitle:title key:_key keyColor:_tagAttribute.keyColor];
        } else {
            cell.titleLabel.text = title;
        }
        if ([self.selectedTags containsObject:self.tags[indexPath.item]]) {
            if (_tagAttribute.selectedBorderColor != nil){
                cell.viewBox.layer.borderColor = _tagAttribute.selectedBorderColor.CGColor;
            }
            cell.titleLabel.textColor = _tagAttribute.selectedTextColor;
            cell.viewBox.backgroundColor = _tagAttribute.selectedBackgroundColor;
        }
    }
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    HXTagCollectionViewFlowLayout *layout = (HXTagCollectionViewFlowLayout *)collectionView.collectionViewLayout;
    CGSize maxSize = CGSizeMake(collectionView.frame.size.width - layout.sectionInset.left - layout.sectionInset.right, layout.itemSize.height);
    
    CGRect frame = CGRectZero;
    if (indexPath.item < _tags.count) {
        frame = [_tags[indexPath.item] boundingRectWithSize:maxSize
                                                    options:NSStringDrawingUsesFontLeading|
                                                            NSStringDrawingUsesLineFragmentOrigin
                                                 attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:_tagAttribute.titleSize]}
                                                    context:nil];
    }
    if (_tagAttribute.haveCloseBtn) {
        frame.size.width += (_tagAttribute.closeBtnWidth - _tagAttribute.closeBtnIgnoreWidth);
    }
//    CGSize size = CGSizeMake(frame.size.width + _tagAttribute.tagSpace , layout.itemSize.height);
    CGSize size = CGSizeMake( (self.size.width - _layout.sectionInset.left*2 - _tagAttribute.tagSpace*2)/3 , layout.itemSize.height);
    return size;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selectedStyle){
        HXTagCollectionViewCell *cell = (HXTagCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
        
        if (_isMultiSelect){
            if ([self.selectedTags containsObject:self.tags[indexPath.item]]) {
                cell.viewBox.backgroundColor = _tagAttribute.normalBackgroundColor;
                cell.titleLabel.textColor = _tagAttribute.textColor;
                [self.selectedTags removeObject:self.tags[indexPath.item]];
            }else{
                cell.viewBox.backgroundColor = _tagAttribute.selectedBackgroundColor;
                cell.titleLabel.textColor = _tagAttribute.selectedTextColor;
                [self.selectedTags addObject:self.tags[indexPath.item]];
            }
            if (_completion) {
                _completion(self.selectedTags, indexPath.item);
            }
        }else{
            if (![self.selectedTags containsObject:self.tags[indexPath.item]]){
                [self.selectedTags removeAllObjects];
                [self.selectedTags addObject:self.tags[indexPath.item]];
                [self reloadData];
                if (_completion) {
                    _completion(self.selectedTags, indexPath.item);
                }
            }
        }
    }else{
        if (_completion) {
            _completion(self.selectedTags,indexPath.item);
        }
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _tags.count;
}

// 设置文字中关键字高亮
- (NSMutableAttributedString *)searchTitle:(NSString *)title key:(NSString *)key keyColor:(UIColor *)keyColor {
    
    NSMutableAttributedString *titleStr = [[NSMutableAttributedString alloc] initWithString:title];
    NSString *copyStr = title;
    
    NSMutableString *xxstr = [NSMutableString new];
    for (int i = 0; i < key.length; i++) {
        [xxstr appendString:@"*"];
    }
    
    while ([copyStr rangeOfString:key options:NSCaseInsensitiveSearch].location != NSNotFound) {
        NSRange range = [copyStr rangeOfString:key options:NSCaseInsensitiveSearch];
        [titleStr addAttribute:NSForegroundColorAttributeName value:keyColor range:range];
        copyStr = [copyStr stringByReplacingCharactersInRange:NSMakeRange(range.location, range.length) withString:xxstr];
    }
    return titleStr;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _collectionView.frame = self.bounds;
}

#pragma mark - 懒加载
- (NSMutableArray *)selectedTags{
    if (!_selectedTags) {
        _selectedTags = [NSMutableArray array];
    }
    return _selectedTags;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:_layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = UIColor.clearColor; 
        [_collectionView registerClass:[HXTagCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    }
    _collectionView.collectionViewLayout = _layout;
    if (_layout.scrollDirection == UICollectionViewScrollDirectionVertical) {
        _collectionView.showsVerticalScrollIndicator = YES;
        _collectionView.showsHorizontalScrollIndicator = NO;
    } else {
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
    }
    
    _collectionView.frame = self.bounds;
    return _collectionView;
}

+ (CGFloat)getHeightWithTags:(NSArray *)tags layout:(HXTagCollectionViewFlowLayout *)layout tagAttribute:(HXTagAttribute *)tagAttribute width:(CGFloat)width{
    
    CGFloat contentHeight = 0;
    if (!layout) {
        layout = [[HXTagCollectionViewFlowLayout alloc] init];
    }
    
    if (!tagAttribute) {
        tagAttribute = [[HXTagAttribute alloc] init];
    }
    
    //cell的高度 = 顶部 + 高度
    contentHeight = layout.sectionInset.top + layout.itemSize.height;

    CGFloat originX = layout.sectionInset.left;
    CGFloat originY = layout.sectionInset.top;
    
    for (NSInteger i = 0; i < tags.count; i++) {
        CGSize maxSize = CGSizeMake(width - layout.sectionInset.left - layout.sectionInset.right, layout.itemSize.height);
        
        CGRect frame = [tags[i] boundingRectWithSize:maxSize
                                             options:NSStringDrawingUsesFontLeading|
                                                     NSStringDrawingUsesLineFragmentOrigin
                                          attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:tagAttribute.titleSize]}
                                             context:nil];
        
        if (tagAttribute.haveCloseBtn) {
            frame.size.width += (tagAttribute.closeBtnWidth - tagAttribute.closeBtnIgnoreWidth);
        }
        
        CGSize itemSize = CGSizeMake(frame.size.width + tagAttribute.tagSpace, layout.itemSize.height);
        
        if (layout.scrollDirection == UICollectionViewScrollDirectionVertical) {
            //垂直滚动, 当前CollectionViewCell的起点 + 当前CollectionViewCell的宽度 + 当前CollectionView距离右侧的间隔 > collectionView的宽度
            if ((originX + itemSize.width + layout.sectionInset.right/2) > width) {
                originX = layout.sectionInset.left;
                originY += itemSize.height + layout.minimumLineSpacing;
                contentHeight += itemSize.height + layout.minimumLineSpacing;
            }
        }
        originX += itemSize.width + layout.minimumInteritemSpacing;
    }
    contentHeight += layout.sectionInset.bottom;
    return contentHeight;
}
+ (CGFloat)getWidthWithTags:(NSArray *)tags
                     layout:(HXTagCollectionViewFlowLayout *)layout
               tagAttribute:(HXTagAttribute *)tagAttribute
                      height:(CGFloat)height {
    
    CGFloat contentWidth = 0;
    
    if (!layout) {
        layout = [[HXTagCollectionViewFlowLayout alloc] init];
    }
    
    if (!tagAttribute) {
        tagAttribute = [[HXTagAttribute alloc] init];
    }
    
    // 初始设置：宽度 = 左边距
    contentWidth = layout.sectionInset.left;
    
    CGFloat originX = layout.sectionInset.left;
    CGFloat originY = layout.sectionInset.top;
    
    for (NSInteger i = 0; i < tags.count; i++) {
        CGSize maxSize = CGSizeMake(CGFLOAT_MAX, height - layout.sectionInset.top - layout.sectionInset.bottom);
        
        CGRect frame = [tags[i] boundingRectWithSize:maxSize
                                             options:NSStringDrawingUsesFontLeading |
                                                     NSStringDrawingUsesLineFragmentOrigin
                                          attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:tagAttribute.titleSize]}
                                             context:nil];
        
        if (tagAttribute.haveCloseBtn) {
            frame.size.width += (tagAttribute.closeBtnWidth - tagAttribute.closeBtnIgnoreWidth);
        }
        
        CGSize itemSize = CGSizeMake(frame.size.width + tagAttribute.tagSpace, layout.itemSize.height);
        
        if (layout.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
            // 水平滚动: 当前Cell起点 + 当前Cell宽度 + 当前距离右侧间隔 > 可用高度
            if ((originY + itemSize.height + layout.minimumLineSpacing) > height) {
                originY = layout.sectionInset.top;
                originX += itemSize.width + layout.minimumInteritemSpacing;
                contentWidth += itemSize.width + layout.minimumInteritemSpacing;
            }
        }
        originY += itemSize.height + layout.minimumLineSpacing;
    }
    
    // 加上右侧边距
    contentWidth += layout.sectionInset.right;
    
    return contentWidth;
}
@end
